package cn.creditease.std.context;

import cn.creditease.std.config.JobConsumerConfig;
import cn.creditease.std.dao.JobDAO;
import cn.creditease.std.factory.JobAlloterFactory;
import cn.creditease.std.utils.IpUtils;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import lombok.Data;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

/**
 * @Description: job分发上下文
 * @Author: kai.yang
 * @Date: 2019-08-13 17:19
 */
@Data
public class JobAlloterContext {

    private static JobAlloterContext jobAlloterContext;

    /**
     * 数据源
     */
    DataSource dataSource;

    /**
     * 消费端id
     */
    String customerId = IpUtils.getLocalIp();


    /**
     * 对应job消费者配置
     */
    Map<String, JobConsumerConfig> jobConsumerConfigMap = new HashMap() {
        {
            this.put("default", new JobConsumerConfig());

        }

        /**
         * 未配置任务消费端时采用默认配置
         * @param key
         * @return
         */
        @Override
        public Object get(Object key) {
            Object o = super.get(key);
            if (o == null) {
                return super.get("default");
            }
            return o;
        }


    };

    JobAlloterFactory jobAlloterFactory;


    /**
     * 获取全局唯一的job分发上下文
     */
    public static JobAlloterContext getContext() {
        return JobAlloterContext.jobAlloterContext;
    }

    /**
     * 初始化分发器
     */
    public static void init(DataSource dataSource, String consumerId, Map jobConsumerConfigMap,
        JobAlloterFactory jobAlloterFactory) {
        JobAlloterContext jobAlloterContext = new JobAlloterContext();
        if (!StringUtils.isEmpty(consumerId)) {
            jobAlloterContext.setCustomerId(consumerId);
        }
        jobAlloterContext.dataSource = dataSource;
        if (!CollectionUtils.isEmpty(jobConsumerConfigMap)) {
            jobAlloterContext.jobConsumerConfigMap = jobConsumerConfigMap;
        }
        jobAlloterContext.jobAlloterFactory = jobAlloterFactory;
        JobAlloterContext.jobAlloterContext = jobAlloterContext;

        JobDAO.newInstance().setDataSource(dataSource);

    }

}
